package com.example.popwindowlibrary

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.PopupWindow

class TrolleyPopWindow (
    private val context: Context,
    private val heightDp: Int = 60
) {

    private val popupWindow: PopupWindow

    init {
        // Inflate the content view
        val inflater = LayoutInflater.from(context)
        val contentView: View = inflater.inflate(R.layout.popwindow_trolley, null)

        // Get screen height
        val displayMetrics = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        //获取状态栏高度
        val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
        val statusBarHeight = if (resourceId > 0) {
            context.resources.getDimensionPixelSize(resourceId)
        } else {
            0
        }
        //获取屏幕高度
        val screenHeight = displayMetrics.heightPixels

        // Convert dp to pixels
        val dpToPx = context.resources.displayMetrics.density
        val heightInPx = (heightDp * dpToPx).toInt()

        // Calculate popup height
        val popupHeight = screenHeight - heightInPx + statusBarHeight

        // Initialize PopupWindow
        popupWindow = PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, popupHeight)
        popupWindow.isFocusable = false
        popupWindow.isClippingEnabled = false//覆盖状态栏
        popupWindow.setBackgroundDrawable(null)
        val otherView=contentView.findViewById<View>(R.id.other_view)
        otherView.setOnClickListener {
            dismiss()
        }
    }
    fun isShowing():Boolean{
        return popupWindow.isShowing
    }
    fun showAtLocation(anchorView: View, gravity: Int = Gravity.TOP, x: Int = 0, y: Int = 0) {
        popupWindow.showAtLocation(anchorView, gravity, x, y)
    }

    fun dismiss() {
        if (popupWindow.isShowing) {
            popupWindow.dismiss()
        }
    }

    fun setBackgroundDrawable(drawable: Drawable?) {
        popupWindow.setBackgroundDrawable(drawable)
    }

    fun setFocusable(focusable: Boolean) {
        popupWindow.isFocusable = focusable
    }
}